﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Text;
using System.Threading;
using System.IO;
using System.IO.Ports;


namespace YBOT_Field_Control
{
    public class XBee
    {
        public struct XBeeNode { public string highAddress; public string lowAddress; public string nodeID; public string data;};   //XBeeNode Structure
        public XBeeNode[] xbNode = new XBeeNode[30];                                                                                //Create Node
        public StringBuilder xbReceivedData = new StringBuilder();                                                                  //Recieved Data on Xbee port
        public SerialPort xbPort = new SerialPort("COM4", 115200);                                                                          //XBee Port Default Com port
        public string DataIn;                                                                                                       //Data Strings

        /// <summary>
        /// Recieves Data from XBee Port
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void Port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort sp = (SerialPort)sender;     //New Serial Port
            DataIn = null;                          //Null Data String
            try
            {
                xbReceivedData.Clear();                 //Clear previous data
                xbReceivedData.Append(sp.ReadLine());   //Add new recieved data
                DataIn = xbReceivedData.ToString();     //Store in DataIn
            }
            catch { }

            //if (DataIn != null)
            //{
            //    string[] temp = DataIn.Split('\t', '\r');                         //Split the line into seperate strings @ tabs & end of line
            //    //If the first string is Tower and the array lenght is > 3
            //    if (temp[0] == "Tower" && temp.Length > 3)
            //    {
            //        int i = Convert.ToInt16(temp[1]);   //i = tower number
            //        xbNode[i].data = temp[2];           //Store data string in node's data
            //    }
            //    //If the first string is OVERRIDE and array length > 2
            //    else if (temp[0] == "OVERRIDE" && temp.Length > 2)
            //    {
            //        int i = (Convert.ToInt16(temp[1]) + 20);    //i = tower number + 20 (used for non-tower nodes)
            //        xbNode[i].data = temp[2];                   //Store data string in node's data
            //    }
            //}
        }

        /// <summary>
        /// Starts XBee Port to recieve data
        /// </summary>
        /// <param name="port">port name as string "COM_"</param>
        public void Startup()
        {
            //If port is null use default port
            if (xbPort.PortName == null) xbPort.PortName = "COM4";
            //If port is not open and port is not null
            if (!xbPort.IsOpen)
            {
                try
                {
                    xbPort.Open();  //Open Port
                    xbPort.DataReceived += new SerialDataReceivedEventHandler(Port_DataReceived);   //Start receiving data
                }
                catch
                {
                }
            }

        }

        public void Startup(string port)
        {
            //If port is null use default port
            if (port != null) xbPort.PortName = port; 

            //If port is not open and port is not null
            if (!xbPort.IsOpen && port != null)
            {
                try
                {
                    xbPort.Open();  //Open Port
                    xbPort.DataReceived += new SerialDataReceivedEventHandler(Port_DataReceived);   //Start receiving data
                }
                catch
                {
                }
            }
            
        }

        /// <summary>
        /// Closes XBee Port
        /// </summary>
        public void Shutdown()
        {
            //If port is onen close the port
            if (xbPort.IsOpen) xbPort.Close();
        }

        /// <summary>
        /// Sends data to destination node
        /// </summary>
        /// <param name="_data">Data as a string</param>
        public void Send(string _data)
        {
            try
            {
                //If port is opne
                if (xbPort.IsOpen)
                {
                    //Send data
                    xbPort.Write(_data + "\r\n");
                }
            }
            catch { };
        }


        ///// <summary>
        ///// Change which node to send data to
        ///// </summary>
        ///// <param name="TowerNum">Number of Tower</param>
        //public void Node(int TowerNum)
        //{
        //    string sn = xbNode[TowerNum].lowAddress;                //set string to node's low address
        //    try
        //    {
        //        string command = "+++";                             //Build command string
        //        byte[] bytes = Encoding.UTF8.GetBytes(command);     //Encode command in bytes
        //        xbPort.Write(bytes, 0, bytes.Length);               //Send command string
        //        Thread.Sleep(300);                                  //Wait 300 milliseconds
        //        command = "ATDL" + sn + "\r";                       //Command = change destination low address to new low address
        //        bytes = Encoding.UTF8.GetBytes(command);            //Encode command in bytes
        //        xbPort.Write(bytes, 0, bytes.Length);               //Send command string
        //        Thread.Sleep(300);                                  //Wait 300 milliseconds
        //        command = "ATWR" + "\r";                            //Command = write to memory
        //        bytes = Encoding.UTF8.GetBytes(command);            //Encode command in bytes
        //        xbPort.Write(bytes, 0, bytes.Length);               //Send command string
        //    }
        //    catch { };
        //}
        
        ///// <summary>
        ///// Locates XBee nodes
        ///// </summary>
        //public void LocateNodes()
        //{
        //    //Path to XBeeConfig file
        //    string path = Environment.ExpandEnvironmentVariables(@"%USERPROFILE%\Desktop\YBOT Field Control Program Files\Setup Files");
        //    //File name
        //    string file = path + @"\XBTowerConfig.txt";

        //    try
        //    {
        //        //If directory does not exists
        //        if (!Directory.Exists(path))
        //        {
        //            Directory.CreateDirectory(path);    //Create Path
        //        }
        //    }
        //    catch
        //    {
        //        //If that didn't work then set path to null
        //        path = null;
        //    }

        //    string LineIn = null;                                                   //Null LineIn
        //    if (File.Exists(file))                                                  //If file is there
        //    {
        //        File.OpenRead(file);                                                //Open the file
        //        StreamReader TowerConfigFile = new StreamReader(file);              //Read the file
        //        for (int i = 0; i < xbNode.Length; i++)                             //For a given number of devices
        //        {
        //            LineIn = TowerConfigFile.ReadLine();                            //Read line
        //            if (LineIn != null)                                             //If LineIn is not null
        //            {
        //                string[] temp = LineIn.Split('\t');                         //Split the line into seperate strings @ tabs
        //                if (temp.Length >= 3)                                       //If temp length is > than 3
        //                {
        //                    xbNode[i].highAddress = temp[0];                        //Store tower's high address
        //                    xbNode[i].lowAddress = temp[1];                         //Store tower's address
        //                    xbNode[i].nodeID = temp[2];                             //Store tower's ID
        //                }
        //            }

        //        }
        //        TowerConfigFile.Close();                                            //Close the file
        //    }

        //    else                                                                    //If the file is not there
        //    {
        //    }
        //    LogWrite("Located Nodes Completed");                                    //Record Complete
        //}

        ///// <summary>
        ///// Current YBOT Directory
        ///// </summary>
        ///// <returns>returns path</returns>
        //public string YBOTFilePath()
        //{
        //    //Store date as a string
        //    string date = DateTime.Today.ToLongDateString();

        //    //Directory path for YBOT 1 on the user's desktop
        //    string YBOTpath = Environment.ExpandEnvironmentVariables(@"%USERPROFILE%\Desktop\YBOT Field Control Program Files");

        //    //Path for todays date
        //    string path = YBOTpath + @"\" + date;

        //    //Check to see if folder exists if not then make it; fail no path is created
        //    try
        //    {
        //        //If directory does not exist
        //        if (!Directory.Exists(YBOTpath))
        //        {
        //            //Create paths
        //            Directory.CreateDirectory(YBOTpath);
        //            Directory.CreateDirectory(path);
        //        }
        //        //If directory does not exist
        //        else if (!Directory.Exists(path))
        //        {
        //            //Create directory
        //            Directory.CreateDirectory(path);
        //        }
        //    }
        //    catch
        //    {   
        //        //If that didn't wory set path to null
        //        path = null;
        //    }

        //    //Return path name
        //    return path;
        //}

        ///// <summary>
        ///// Updates Log file
        ///// </summary>
        ///// <param name="text">text to write to log as string</param>
        //private void LogWrite(string text)
        //{
        //    string path = (YBOTFilePath() + @"\Logs");  //Log Directory
        //    string file = "\\YBOT_XBlog.txt";        //Log file name

        //    //Try and write data to file, return if fail
        //    try
        //    {
        //        if (!Directory.Exists(path)) Directory.CreateDirectory(path);                                           //If directory does not exist create it
        //        string date = DateTime.Today.ToShortDateString();                                                       //Build date string
        //        string time = DateTime.Now.ToLongTimeString() + ":" + DateTime.Now.Millisecond.ToString();              //Build time string
        //        text = (date + " " + time + " " + text);                                                                //Build string with time stamp
        //        FileStream fs = new FileStream((path + file), FileMode.Append, FileAccess.Write, FileShare.Write);      //Open file
        //        fs.Close();
        //        StreamWriter sw = new StreamWriter((path + file), true, Encoding.ASCII);                                
        //        sw.WriteLine(text);                                                                                     //Write text
        //        sw.Close();                                                                                             //Close file
        //    }
        //    catch
        //    {
        //        return;                                                                                                 //If that didn't work return to program
        //    }

        //}

    }
}
